<button>test</button>
<input type="file" id="imgfile" method="post" enctype="multipart/form-data">
<button type="button" onclick="ToBase64();">show</button>
<button onclick="DrawRec()">Rectangle</button>
<!-- <script src="http://d3js.org/d3.v4.min.js" charset="utf-8"></script> -->
<script src="https://d3js.org/d3.v6.min.js" charset="utf-8"></script>

<button onclick="DrawCircle()">test data join</button>
<button onclick="MoveCircle()">move</button>
<button onclick="testdrawLine('#canvas',20,50,170,120,3,'black')">line</button>
<button onclick="testdrawRectangle('#canvas',20,50,170,120,3,'black','white')">rect</button>
<button onclick="removeLine('#canvas')">remove</button>
<button onclick="drawenable=true;createRect('#canvas');">newrect</button>
<button onclick="frontRectangle('#canvas')">front</button>
<button onclick="drawenable=true;createStar('#canvas');">draw star</button>
<script>
    tl = undefined

    selectedrectid = undefined
    function moveline(canvasId, xProperty, yProperty, yProperty, line, evt) {
        let svg = this.getCanvas(canvasId)
        svg.select('#' + line.attr("id")).
            attr(xProperty, evt.evt.offsetX).
            attr(yProperty, evt.evt.offsetY)

    }
    currentX = 0, currentY = 0
    isCapture = false
    let currentdragline = undefined
    let rectactivepointdrag = (target) => {
        d3.drag()
            // .origin(function (d) {  //设置起点坐标
            //     var t = d3.select(this);
            //     let r =
            //     {
            //         x: t.attr("cx"),
            //         y: t.attr("cy")
            //     };
            //     return r
            //     // return { x: d.cx, y: d.cy } //起点坐标为被拖动物体的圆心坐标
            // })
            .on("start", function (a) { //dragstart的监听器
                console.log("拖曳开始");
            })
            .on("end", function (d) {  //dragend的监听器
                console.log("搁曳结束");
            })
            .on("drag", function (d) {
                //console.log(d);

                let mx = d3.event.x
                let my = d3.event.y

                var t = d3.select(this);
                if (t.attr("tag") === "l") {
                    let right = Number(target.attr("x")) + Number(target.attr("width"))

                    if (mx < right) {
                        t.attr("cx", mx)
                        target.attr("x", mx)
                        target.attr("width", right - mx)
                    }
                }

                if (t.attr("tag") === "t") {
                    let bottom = Number(target.attr("y")) + Number(target.attr("height"))

                    if (my < bottom) {
                        t.attr("cy", my)
                        target.attr("y", my)
                        target.attr("height", bottom - my)
                    }
                }

                if (t.attr("tag") === "r") {
                    if (mx > Number(target.attr("x"))) {
                        t.attr("cx", mx)
                        target.attr("width", mx - Number(target.attr("x")))
                    }
                }

                if (t.attr("tag") === "b") {
                    if (my > Number(target.attr("y"))) {
                        t.attr("cy", my)
                        target.attr("height", my - Number(target.attr("y")))
                    }
                }

            });

    }
    function activeRect(canvasId, target, pointR) {
        selectedrectid = target.attr('id')
        console.log(selectedrectid);
        let baseid = target.attr("id")
        let line = undefined
        var drag = d3.drag()
            // .origin(function (d) {  //设置起点坐标
            //     var t = d3.select(this);
            //     let r =
            //     {
            //         x: d3.event.offsetX,
            //         y: d3.event.offsetY
            //     };

            //     return r
            //     // return { x: d.cx, y: d.cy } //起点坐标为被拖动物体的圆心坐标
            // })
            .on("start", function (event) { //dragstart的监听器
                console.log("拖曳开始");

                currentdragline = testdrawLine(canvasId, event.sourceEvent.offsetX, event.sourceEvent.offsetY, event.sourceEvent.offsetX, event.sourceEvent.offsetY, 2, 'black')
                target.attr('outlineids', target.attr('outlineids') + ',' + currentdragline.attr('id'))

                event.sourceEvent.stopPropagation();
            })
            .on("end", function (event) {  //dragend的监听器
                console.log("搁曳结束");

                event.sourceEvent.stopPropagation();
            })
            .on("drag", function (event) {
                //console.log(d);

                let mx = event.sourceEvent.offsetX
                let my = event.sourceEvent.offsetY
                console.log(event);

                var t = d3.select(this);

                currentdragline.attr('x2', mx)
                currentdragline.attr('y2', my)
                event.sourceEvent.stopPropagation();
                // if (t.attr("tag") === "l") {
                //     let right = Number(target.attr("x")) + Number(target.attr("width"))

                //     if (mx < right) {
                //         t.attr("cx", mx)
                //         target.attr("x", mx)
                //         target.attr("width", right - mx)
                //     }
                // }

                // if (t.attr("tag") === "t") {
                //     let bottom = Number(target.attr("y")) + Number(target.attr("height"))

                //     if (my < bottom) {
                //         t.attr("cy", my)
                //         target.attr("y", my)
                //         target.attr("height", bottom - my)
                //     }
                // }

                // if (t.attr("tag") === "r") {
                //     if (mx > Number(target.attr("x"))) {
                //         t.attr("cx", mx)
                //         target.attr("width", mx - Number(target.attr("x")))
                //     }
                // }

                // if (t.attr("tag") === "b") {
                //     if (my > Number(target.attr("y"))) {
                //         t.attr("cy", my)
                //         target.attr("height", my - Number(target.attr("y")))
                //     }
                // }

            });


        let r = []

        let leftx = target.attr("x")
        let lefty = Number(target.attr("y")) + Number(target.attr("height")) / 2
        let topx = Number(target.attr("x")) + Number(target.attr("width")) / 2
        let topy = target.attr("y")
        let rightx = Number(target.attr("x")) + Number(target.attr("width"))
        let righty = Number(target.attr("y")) + Number(target.attr("height")) / 2
        let bottomx = Number(target.attr("x")) + Number(target.attr("width")) / 2
        let bottomy = Number(target.attr("y")) + Number(target.attr("height"))


        let activePoint = drawCircle(canvasId, leftx, lefty, pointR, "1px", "black", "white")
        activePoint.call(drag);
        activePoint.attr('tag', "l")
        activePoint.attr("id", 'activepointl' + baseid)
        activePoint.attr("class", "activepoint")//所有的激活点都是同一类
        activePoint.on("mouseover", function (d, i) {

            d3.select(this).attr("fill", "black"); //当鼠标移到元素上时，元素为黄色						
        })
            .on("mouseout", function (d, i) {
                d3.select(this)//当鼠标移到元素上时，元素过渡到原来的颜色
                    .transition()
                    .duration(500)
                    .attr("fill", "white");
            })
            .on("mouseup", function (d, i) {
                if (currentdragline !== undefined) {
                    target.attr('inlineids', target.attr('inlineids') + ',' + currentdragline.attr('id'))
                    currentdragline = undefined

                }
            })
        target.attr("activepointleft", activePoint)

        r.push(activePoint)

        activePoint = drawCircle(canvasId, topx, topy, pointR, "1px", "black", "white")
        activePoint.call(drag);
        activePoint.attr('tag', "t")
        activePoint.attr("id", 'activepointt' + baseid)
        activePoint.on("mouseover", function (d, i) {
            d3.select(this).attr("fill", "black"); //当鼠标移到元素上时，元素为黄色						
        })
            .on("mouseout", function (d, i) {
                d3.select(this)//当鼠标移到元素上时，元素过渡到原来的颜色
                    .transition()
                    .duration(500)
                    .attr("fill", "white");
            });
        activePoint.attr("class", "activepoint")
        target.attr("activepointtop", activePoint)
        r.push(activePoint)

        activePoint = drawCircle(canvasId, rightx, righty, pointR, "1px", "black", "white")
        activePoint.call(drag);
        activePoint.attr('tag', "r")
        activePoint.attr("id", 'activepointr' + baseid)
        activePoint.on("mouseover", function (d, i) {

            d3.select(this).attr("fill", "black"); //当鼠标移到元素上时，元素为黄色						
        })
            .on("mouseout", function (d, i) {
                d3.select(this)//当鼠标移到元素上时，元素过渡到原来的颜色
                    .transition()
                    .duration(500)
                    .attr("fill", "white");
            });
        target.attr("activepointright", activePoint)
        activePoint.attr("class", "activepoint")
        r.push(activePoint)

        activePoint = drawCircle(canvasId, bottomx, bottomy, pointR, "1px", "black", "white")
        activePoint.call(drag);
        activePoint.attr('tag', "b")
        activePoint.attr("id", 'activepointb' + baseid)
        activePoint.on("mouseover", function (d, i) {
            d3.select(this).attr("fill", "black"); //当鼠标移到元素上时，元素为黄色						
        })
            .on("mouseout", function (d, i) {
                d3.select(this)//当鼠标移到元素上时，元素过渡到原来的颜色
                    .transition()
                    .duration(500)
                    .attr("fill", "white");
            });
        target.attr("activepointbottom", activePoint)
        activePoint.attr("class", "activepoint")
        r.push(activePoint)


        return r
    }
    function activeLine(canvasId, targetLine, pointR) {
        let r = []
        var drag = d3.behavior.drag()
            .origin(function (d) {  //设置起点坐标
                var t = d3.select(this);
                let r =
                {
                    x: t.attr("cx"),
                    y: t.attr("cy")
                };
                return r
                // return { x: d.cx, y: d.cy } //起点坐标为被拖动物体的圆心坐标
            })
            .on("dragstart", function (a) { //dragstart的监听器
                console.log("拖曳开始");
            })
            .on("dragend", function (d) {  //dragend的监听器
                console.log("搁曳结束");
            })
            .on("drag", function (d) {
                //console.log(d);

                let mx = d3.event.x
                let my = d3.event.y

                var t = d3.select(this);
                t
                    // 将d3.event.x赋值给被绑定的数据，再将cx属性设置为该值
                    .attr("cx", mx)
                //将d3.event.y赋值给被绑定的数据，再将cy属性设置为该值
                t.attr("cy", my);
                targetLine.attr(t.attr("tagx"), mx)
                targetLine.attr(t.attr("tagy"), my)

                event.stopPropagation();
            });

        let activePoint = drawCircle(canvasId, targetLine.attr("x1"), targetLine.attr("y1"), pointR, "1px", "black", "white")
        activePoint.call(drag);
        activePoint.attr('tagx', "x1")
        activePoint.attr('tagy', "y1")
        // activePoint.on("mousedown", (s, evt) => {
        //     console.log(evt);
        //     isCapture = true

        // })
        // activePoint.on("mousemove", (evt) => {
        //     console.log('moving');
        // })
        // activePoint.on("mouseup", (evt) => {
        //     console.log('up!');
        // })
        r.push(activePoint)
        activePoint = drawCircle(canvasId, targetLine.attr("x2"), targetLine.attr("y2"), pointR, "1px", "black", "white")
        activePoint.call(drag);
        activePoint.attr('tagx', "x2")
        activePoint.attr('tagy', "y2")
        r.push(activePoint)
        return r
    }
    function deactive(canvasId, cl) {

    }
    function removeLine(canvasId) {
        let svg = this.getCanvas(canvasId)
        console.log(tl);
        svg.select('#' + tl.attr("id")).remove()
    }
    function getCanvas(canvasId) {
        return d3.select(canvasId)
    }
    function getid(pre) {
        let id = pre;
        let s = new Date();
        id +=
            s.getFullYear().toString() +
            s.getMonth().toString() +
            s.getDate().toString() +
            s.getHours().toString();
        id +=
            s.getMinutes().toString() +
            s.getSeconds().toString() +
            s.getMilliseconds().toString() +
            Math.round(Math.random() * 1000).toString();
        const tsleep = (time) => {
            return new Promise(resolve => setTimeout(resolve, time))
        }
        tsleep(1)
        return id.slice(0, 21);
    }
    function testdrawLine(canvasId, x1, y1, x2, y2, w, c, includeArrow = true) {
        let svg = this.getCanvas(canvasId)
        let line = svg.append("line")
            .attr("id", getid('line'))
            .attr("x1", x1)
            .attr("y1", y1)
            .attr("x2", x2)
            .attr("y2", y2)
            .attr("stroke", c)
            .attr("stroke-width", w)
            .attr("isactive", false)
        if (includeArrow) {
            var defs = svg.append("defs");
            var arrowMarker = defs.append("marker")
                .attr("id", "arrow")
                .attr("markerUnits", "strokeWidth")
                .attr("markerWidth", 12)
                .attr("markerHeight", 12)
                .attr("viewBox", "0 0 12 12")
                .attr("refX", 6)
                .attr("refY", 6)
                .attr("orient", "auto")
                .attr("fill", "#F00")


            var arrow_path = "M-8,2 L7,6 L-8,10 L-4,6 L-8,2";

            arrowMarker.append("path")
                .attr("d", arrow_path)
                .attr("fill", "#00F")
            line.attr("marker-end", "url(#arrow)")

        }
        line.on("click", function () {
            if (line.attr("isactive") === 'false') {
                line.attr("isactive", true)
                activeLine(canvasId, line, 3)

            }
        });
        tl = line
        console.log(line);
        console.log(tl);
        return line
    }
    let dragrect = (canvasId) => {
        let svg = this.getCanvas(canvasId)
        return d3.drag()
            // .origin(function (d) {  //设置起点坐标
            //     var t = d3.select(this);
            //     let r =
            //     {
            //         x: t.attr("x"),
            //         y: t.attr("y")
            //     };

            //     return r
            // })
            .on("start", function (event) { //dragstart的监听器
                console.log("拖曳开始");
                event.sourceEvent.stopPropagation();
            })
            .on("end", function (event) {  //dragend的监听器
                console.log("搁曳结束");
                event.sourceEvent.stopPropagation();
            })
            .on("drag", function (event) {
                //console.log(d);

                let mx = event.x
                let my = event.y
                let dx = event.dx
                let dy = event.dy

                var t = d3.select(this);
                t.attr("x", mx)
                //将d3.event.y赋值给被绑定的数据，再将cy属性设置为该值
                t.attr("y", my);
                if (t.attr("isactive") === 'true') {
                    let lp = svg.select('#activepointl' + t.attr("id"))
                    lp.attr("cx", t.attr("x"))
                    lp.attr("cy", Number(t.attr("y")) + Number(t.attr("height")) / 2)

                    let tp = svg.select('#activepointt' + t.attr("id"))
                    tp.attr("cy", t.attr("y"))
                    tp.attr("cx", Number(t.attr("x")) + Number(t.attr("width")) / 2)

                    let rp = svg.select('#activepointr' + t.attr("id"))
                    rp.attr("cx", Number(t.attr("x")) + Number(t.attr("width")))
                    rp.attr("cy", Number(t.attr("y")) + Number(t.attr("height")) / 2)

                    let bp = svg.select('#activepointb' + t.attr("id"))
                    bp.attr("cx", Number(t.attr("x")) + Number(t.attr("width")) / 2)
                    bp.attr("cy", Number(t.attr("y")) + Number(t.attr("height")))
                }
                console.log('moving lines');
                let outids = t.attr('outlineids') === null ? '' : t.attr('outlineids')

                let ids = outids.split(',')
                ids.forEach(id => {
                    if (id !== 'null' && id !== '') {
                        let r = svg.select('#' + id)
                        if (r !== undefined)
                            r.attr('x1', Number(r.attr('x1')) + dx).attr('y1', Number(r.attr('y1')) + dy)
                    }
                });
                let inids = t.attr('inlineids') === null ? '' : t.attr('inlineids')

                ids = inids.split(',')
                ids.forEach(id => {
                    if (id !== 'null' && id !== '') {
                        let r = svg.select('#' + id)
                        if (r !== undefined)
                            r.attr('x2', Number(r.attr('x2')) + dx).attr('y2', Number(r.attr('y2')) + dy)
                    }
                });
                event.sourceEvent.stopPropagation();
            })
    }
    function frontRectangle(canvasId) {
        if (selectedrectid === undefined) {
            console.log('no selected rect');
            return
        }
        console.log('moving ' + selectedrectid);
        let svg = this.getCanvas(canvasId)
        rect = svg.select('#' + selectedrectid)

        let x = rect.attr('x')
        let y = rect.attr('y')
        let w = rect.attr('width')
        let h = rect.attr('height')

        let clonedrect = this.getCanvas(canvasId).append("rect")
            .attr("id", selectedrectid)
            .attr("class", "node")
            .attr("x", x)
            .attr("y", y)
            .attr("width", w)
            .attr("height", h)
            .attr("fill", rect.attr('fill'))
            //.attr("fill", "red")
            .attr("stroke", rect.attr('stroke'))
            .attr("stroke-width", rect.attr('stroke-width'))
            .attr('inlineids', rect.attr('inlineids'))
            .attr('outlineids', rect.attr('outlineids'))

        clonedrect.on("click", function () {
            if (clonedrect.attr("isactive") === 'false') {
                clonedrect.attr("isactive", true)
                activeRect(canvasId, clonedrect, 3)
            }
            event.stopPropagation();
        });
        clonedrect.call(dragrect(canvasId))
        if (rect.attr("isactive") === 'true') {

            clonedrect.attr("isactive", true)
            activeRect(canvasId, clonedrect, 3)

            svg.select('#activepointl' + selectedrectid).remove()
            svg.select('#activepointt' + selectedrectid).remove()
            svg.select('#activepointr' + selectedrectid).remove()
            svg.select('#activepointb' + selectedrectid).remove()
        }
        //svg.select('#' + selectedrectid).remove()
        console.log('clone success!');
        svg.select('#' + selectedrectid).remove()
        return clonedrect
    }
    function testdrawRectangle(canvasId, x1, y1, x2, y2, w, bc, fc) {

        let svg = this.getCanvas(canvasId)
        // let group = svg.append("g").attr("x", Math.min(x1, x2))
        //     .attr("y", Math.min(y1, y2)).attr("width", Math.abs(x1 - x2))
        //     .attr("height", Math.abs(y1 - y2))
        let rect = svg.append("rect")
            .attr("id", getid('rect'))
            .attr("class", "node")
            .attr("x", Math.min(x1, x2))
            .attr("y", Math.min(y1, y2))
            .attr("width", Math.abs(x1 - x2))
            .attr("height", Math.abs(y1 - y2))
            .attr("fill", fc)
            .attr("stroke", bc)
            .attr("stroke-width", w)
            .attr("isactive", false)
        // let circle = group.append("circle")
        //     .attr("cx", Math.min(x1, x2))
        //     .attr("cy", Math.min(y1, y2))
        //     .attr("r", 3)
        //     .attr("fill", 'yellow')
        //     .attr("stroke", 'black')
        //     .attr("stroke-width", 1)
        //.attr("activefunc", (r) => activeRect(canvasId, r, 3))
        //console.log(rect);
        rect.on("click", function () {
            if (rect.attr("isactive") === 'false') {
                rect.attr("isactive", true)
                activeRect(canvasId, rect, 3)

            }
            event.stopPropagation();
        });
        //rect.attr("activefunc", activeRect)


        rect.call(dragrect(canvasId))
        return rect
    }
    function drawCircle(canvasId, cx, cy, r, w, bc, fc) {
        let svg = this.getCanvas(canvasId)
        let circle = svg.append("circle")
            .attr("cx", cx)
            .attr("cy", cy)
            .attr("r", r)
            .attr("fill", fc)
            .attr("stroke", bc)
            .attr("stroke-width", w)
        return circle
    }
    function testdrawStar(canvasId, x1, y1, x2, y2, w, bc, fc) {
        let svg = this.getCanvas(canvasId)
        let circle = svg.append("circle")
            .attr("cx", cx)
            .attr("cy", cy)
            .attr("r", r)
            .attr("fill", fc)
            .attr("stroke", bc)
            .attr("stroke-width", w)
        return circle
    }
    let drawmode = false
    let drawstartx = 0
    let drawstarty = 0
    let currentRect = undefined
    let drawenable = false
    function setDrawmode(canvasId) {

    }
    function createRect(canvasId) {
        let svg = this.getCanvas(canvasId)

        svg.on("mousedown", function (event, i) {
            if (drawenable) {
                drawmode = true
                console.log(event.x);
                let x = event.x
                let y = event.y
                currentRect = testdrawRectangle(canvasId, x, y, x, y, 2, 'black', 'white')
            }
        }, false)
            .on("mouseup", function (event, i) {
                console.log('draw up');
                drawmode = false
                drawenable = false
            }, false)
            .on("mousemove", function (event, i) {
                if (drawenable && drawmode && currentRect !== undefined) {
                    let tx = Number(currentRect.attr('x'))
                    let ty = Number(currentRect.attr('y'))
                    currentRect.attr('width', Math.abs(tx - event.x))
                    currentRect.attr('height', Math.abs(ty - event.y))
                    currentRect.attr('x', Math.min(tx, event.x))
                    currentRect.attr('y', Math.min(ty, event.y))
                }
            }, false)
            .on('click', function (d, i) {
                console.log('canvas click');
                d3.selectAll('.activepoint').remove()
                d3.selectAll('.node').attr("isactive", 'false')
            }, false)
    }
    function createStar(canvasId) {
        // 定义符号生成器
        var symbol = d3.symbol()
            .size(250)
            .type(function (d) { return d; });
        let svg = this.getCanvas(canvasId)
        let circle = svg.append("g")
            .attr("transform", function (d, i) {
                var x = 100;
                var y = 150;
                return "translate(" + x + ", " + y + ")";
            })
            //.attr('x', 250).attr('y', 200)
            .attr("stroke", 'black')
            .attr("stroke-width", 1)
            .append("path")
            .attr("d", function (d) { return symbol(d3.symbolStar); })
            // .attr("transform", function (d, i) {
            //     var x = 100;
            //     var y = 150;
            //     return "translate(" + x + ", " + y + ")";
            // })
            .attr("fill", 'red')
            .attr("stroke", 'black')
            .attr("stroke-width", 3)
            .append('text')
            .text('text')
            // .attr("x", 25)
            // .attr('y', 25)
            .attr('text-anchor', "middle")

        // 七种图形符号
        var dataSymbol = [d3.symbolCircle, d3.symbolCross, d3.symbolDiamond, d3.symbolSquare,
        d3.symbolStar, d3.symbolTriangle, d3.symbolWye];


        // 定义十种颜色
        var colors = d3.scaleOrdinal(d3.schemeCategory10);

        // 绘制
        svg.selectAll("path")
            .data(dataSymbol)
            .enter()
            .append("path")
            .attr("d", function (d) { return symbol(d); })
            .attr("transform", function (d, i) {
                var x = 10;
                var y = 10 + i * 80;
                return "translate(" + x + ", " + y + ")";
            })
            .attr("fill", function (d, i) { return colors(i); })

    }


    isDeawRec = false
    startX = 0
    startY = 0
    let td = [
        { x: 0, y: 60 }, { x: 20, y: 25 }, { x: 99, y: 120 }
    ]
    circle = undefined
    function DrawCircle() {
        var svg = d3.select("#canvas")
        circle = svg.selectAll("circle")
            .data(td)

        updatecircle()
    }
    function updatecircle() {
        circle.enter().append("circle")
            .attr("r", 10);
        circle.exit().remove();
        circle
            .attr("cx", function (d) { return d.x; })
            .attr("cy", function (d) { return d.y; });


        console.log(circle.enter());
        console.log(circle.exit());
    }
    function MoveCircle() {

        td[0]['x'] += 200
        td[2]['y'] += 30
        td.push({
            x: 0, y: 0
        })
        updatecircle()

        // circle
        //     .attr("cx", function (d) { return d.x; })
        //     .attr("cy", function (d) { return d.y; })
        //.attr("r", 15)


        console.log(td);
    }
    // let data = [
    //     {
    //         startX: 15,
    //         startY: 20,
    //         width: 100,
    //         height: 150,
    //         fill: 'red'
    //     },
    //     {
    //         startX: 55,
    //         startY: 29,
    //         width: 120,
    //         height: 150,
    //         fill: 'blue'
    //     }
    // ]

    let data = [
        {
            X1: 15,
            Y1: 20,
            X2: 100,
            Y2: 150,
            fill: 'red'
        },
        {
            X1: 55,
            Y1: 29,
            X2: 120,
            Y2: 150,
            fill: 'blue'
        }
    ]
    rectdata = []
    function DrawRec() {
        isDeawRec = true

    }
    let rect = undefined
    function mousedown(evt) {
        if (isDeawRec) {
            startX = evt.offsetX
            startY = evt.offsetY
            // rectdata.X1 = rectdata.X2 = evt.offsetX
            // rectdata.y1 = rectdata.Y2 = evt.offsetY
            rectdata.push({
                X1: evt.offsetX,
                Y1: evt.offsetY,
                X2: evt.offsetX + 1,
                Y2: evt.offsetY + 1,
                fill: 'blue'
            })
            var svg = d3.select("#canvas")     //选择文档中的body元素
            console.log(svg);
            svg.selectAll("rect")
                .data(rectdata)
                .enter().append("rect")
                .attr("x", function (d) { return Math.min(d.X2, d.X2); })
                .attr("y", function (d) { return Math.min(d.Y2, d.Y2); })
                .attr("width", function (d) { return Math.abs(d.X2 - d.X2);; })
                .attr("height", function (d) { return Math.abs(d.Y2 - d.Y2); })
                .attr("fill", function (d) { return d.fill; })
                .on("mouseover", function (d, i) {
                    d3.select(this).attr("fi11", "yellow"); //当鼠标移到元素上时，元素为黄色						
                })
                .on("mouseout", function (d, i) {
                    d3.select(this)//当鼠标移到元素上时，元素过渡到原来的颜色
                        .transition()
                        .duration(500)
                        .attr("fill", "steelblue");
                });

            // rect = svg.append("rect")  //添加一个矩形
            //     .attr("x", startX)
            //     .attr("y", startY)
            //     .attr("stroke", 'green')
            //     .attr("fill", "transparnet")
            //     .attr("width", 0)
            //     .attr("height", 0)
            //     .attr("onmousedown", function select(evt) {

            //     })
            //     .attr("onmousemove", function moving(evt) {

            //     })
            //     .attr("onmouseup", function moving(evt) {

            //     })
        }
    }
    isDeawRec = false
    function mousemoving(evt) {
        if (isDeawRec) {
            if (rectdata !== undefined && rectdata.length > 0) {
                rectdata.X2 = evt.offsetX
                rectdata.Y2 = evt.offsetY
            }
            // rect

            //     .attr("width", evt.offsetX - startX)
            //     .attr("height", evt.offsetY - startY)
            // .attr("fill", "red")


            //console.log(evt);
        }
    }
    function mouseup(evt) {

        isDeawRec = false
        rect = undefined
        rectdata = []
    }

    function ToBase64() {

        /*转换base64*/
        var img = document.getElementById('imgfile')
        var imgFile = new FileReader();
        imgFile.readAsDataURL(img.files[0]);

        imgFile.onload = function () {
            var imgData = this.result; //base64数据  
            console.log(imgData);
            let e = document.getElementById("load")
            console.log(e);
            console.log(e['href']);
            console.log(e.href);
            //e[0].setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', imgData);
            e.href.baseVal = imgData
        }

    }


</script>
<div>
    <svg id='canvas' width="580" height="400" xmlns="http://www.w3.org/2000/svg" fill="gray"
        onmousedown="mousedown(evt)" xmlns:xlink="http://www.w3.org/1999/xlink" onmousemove="mousemoving(evt)"
        onmouseup="mouseup(evt)">
        <!-- Created with Method Draw - http://github.com/duopixel/Method-Draw/ -->
        <g>
            <title>background</title>
            <rect fill="#fff" id="canvas_background" height="402" width="582" y="-1" x="-1" />
            <g display="none" overflow="visible" y="0" x="0" height="100%" width="100%" id="canvasGrid">
                <rect fill="url(#gridpattern)" stroke-width="0" y="0" x="0" height="100%" width="100%">
                    <circle CX="50" CY="100" fill="green"></circle>
                </rect>
            </g>
        </g>
        <g>
            <title>Layer 1</title>
            <image id="load" width="100" height="200" x="100" y="200"
                href="">
            </image>
            <rect x=100 y=200 width=100 height=200 fill="red"></rect>
        </g>
    </svg>
</div>